package com.registry.client.service;

import com.alibaba.fastjson.JSONObject;
import com.registry.client.config.RegistryCentreConfig;
import com.registry.client.config.ServerConfig;
import com.registry.client.config.ServerNameConfig;
import com.utils.HttpClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Service
public class RegistryService {

    private static ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private ServerNameConfig cloudConfig;

    @Autowired
    private RegistryCentreConfig registryCentreConfig;

    /**
     * 服务注册
     */
    public void registry(){

        JSONObject jsonObject = sendHttp(null, "server_registry");
         // 如果注册成功，则启动续约定时任务。该处时启动也是唯一一次调用续约
        if(jsonObject != null && jsonObject.getInteger("code") == 200){
            startRenewal();
            return;
        }
    }

    /**
     * 服务注销
     */
    public void remove(){
        sendHttp(null, "server_remove");
    }

    /**
     * 开始续约
     * 该方法每次启动都会被调用一次，并且仅会被调用一次，因为调用的入口就是spring启动成功后的事件
     */
    public void startRenewal(){
        scheduledExecutorService.scheduleAtFixedRate(new scheduleRenewal(), 3,3, TimeUnit.SECONDS);
    }

    class scheduleRenewal implements Runnable{

        @Override
        public void run() {
            sendHttp(5000L, "server_renewal");
        }
    }

    /**
     * 发送请求
     * @param durationTime  续约时间，null表示是移除/注册服务
     * @param interfactType 调用服务端哪个接口
     */
    public JSONObject sendHttp(Long durationTime, String interfactType){
        // 获取本服务ip与端口拼装的http
        String host = serverConfig.getHost();

        // 配置续约请求参数
        JSONObject object = new JSONObject();
        object.put("serviceAddres", host);
        object.put("serviceName", cloudConfig.getName());
        if(durationTime != null){
            object.put("renewalDuration", 5000);
        }

        // 配置文件中是ip:pord形式
        String httpUrl = "http://" + registryCentreConfig.getServerIp() + ":8848" + "/registry_centre/" + interfactType;
        JSONObject jsonObject = HttpClientUtils.httpPost(httpUrl, object);
        return jsonObject;
    }
}
